import { createRouter, createWebHistory } from "vue-router";

import NProgress from "nprogress"; // 导入 nprogress模块

import "nprogress/nprogress.css"; // 导入样式，否则看不到效果
import localStorage from "@/utils/local-storage";
const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/",
      redirect: "/main",
    },
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/login/login.vue"),
    },
    {
      path: "/main",
      name: "main",
      component: () => import("@/views/main/main.vue"),
    },
    {
      path: "/:pathMatch(.*)*",
      name: "notFound",
      component: () => import("@/views/not-found/not-found.vue"),
    },
  ],
});

router.beforeEach((to) => {
  NProgress.configure({ showSpinner: false });
  NProgress.start(); //开启进度条

  if (to.path !== "/login") {
    const token = localStorage.get("token");
    if (!token) {
      return "/login";
    }
    if (to.path === "/main") {
      return router.getRoutes()[0].path;
    }
  }
});

// 路由加载后
router.afterEach(() => {
  NProgress.done(); //完成进度条
});
export default router;
